package org.budo.support.pagehelper;

import java.util.List;

import org.budo.support.dao.page.Page;

import com.github.pagehelper.PageHelper;

/**
 * @author limingwei2
 */
public class PageHelperUtil {
    public static final ThreadLocal<Page> PAGE_THREAD_LOCAL = new ThreadLocal<Page>();

    public static void startPage(Page page) {
        if (null != page) {
            boolean count = null == page.getCount() || page.getCount(); // 默认要count

            int offset = page.getOffset();
            int pageSize = null == page.getPageSize() ? Page.PAGE_SIZE_DEFAULT : page.getPageSize();

            String orderBy = page.getOrderBy();
            if (null == orderBy) {
                PageHelper.offsetPage(offset, pageSize).setCount(count);
            } else {
                PageHelper.offsetPage(offset, pageSize).setOrderBy(orderBy).setCount(count);
            }

            PAGE_THREAD_LOCAL.set(page);
        }
    }

    @SuppressWarnings("rawtypes")
    public static Number getRecordCount(List<?> list) {
        if (null != list && list instanceof com.github.pagehelper.Page) {
            return ((com.github.pagehelper.Page) list).getTotal();
        } else {
            return 0;
        }
    }
}